package com.sunlands.deskmate.message.handler.storager.interceptor.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.entity.TzChatRecord;
import com.sunlands.deskmate.message.handler.storager.interceptor.Interceptor;
import com.sunlands.deskmate.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import static com.sunlands.deskmate.message.enums.MessageType.*;

/**
 * 保存消息
 */
@Order(100000)
@Slf4j
@Component
public class SaveMessageInterceptor implements Interceptor {

    @Autowired
    private MessageService messageService;

    @Resource(name = "messageHandler")
    private AsyncTaskExecutor messageHandler;

    @Override
    public boolean interceptor(Messages messages) {
        if (!ENTER_PRIVATE_CHAT.getType().equals(messages.getType())
                && !QUIT_PRIVATE_CHAT.getType().equals(messages.getType())
                && !ENTER_GROUP.getType().equals(messages.getType())
                && !QUIT_GROUP.getType().equals(messages.getType())
                && !ENTER_ROOM.getType().equals(messages.getType())
                && !QUIT_ROOM.getType().equals(messages.getType())
        ) {
            messageHandler.execute(() -> saveChatRecord(messages));
        }
        return true;
    }

    private Long saveChatRecord(Messages messages) {
        TzChatRecord record = new TzChatRecord();
        record.setFromUserId(messages.getFromUserId());
        record.setToId(messages.getToId());
        record.setType(messages.getType());
        record.setMessage(messages.getMessage());
        record.setExtras(JSONObject.toJSONString(messages.getExtras()));
        record.setContentId(messages.getContentId());
        record.setContentType(messages.getContentType());
        record.setAckId(messages.getAckId());
        Date now = new Date();
        record.setCreateTime(now);
        messages.setCreateTime(DateFormatUtils.format(now, "yyyy-MM-dd HH:mm:ss"));
        messageService.saveChatRecord(record);
        return record.getId();
    }
}